from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from celery_tasks.static_file.tasks import  get_static_sku_detail_html
from goods.models import SKUImage, SKU


class SKUImagesSerializer(ModelSerializer):

    class Meta:
        model = SKUImage
        fields = '__all__'

    def create(self, validated_data):
        # 重写创建对象方法，ＵＲＬ图片需要传到ｆｓｄｒｆ服务器
        file = self.context['request'].FILES.get('image')
        file_bin = file.read()
        # 创建FastDFS客户端实例
        client = Fdfs_client(settings.FDFS_CONFIG_DIRS)
        # 调用FastDFS客户端上传文件方法
        ret = client.upload_by_buffer(file_bin)
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')
        img = SKUImage.objects.create(sku=validated_data['sku'], image=ret['Remote file_id'])

        # 异步生成静态文件
        get_static_sku_detail_html.delay(img.sku.id)

        return img
    def update(self, instance, validated_data):
        # 重写创建对象方法，ＵＲＬ图片需要传到ｆｓｄｒｆ服务器
        file = self.context['request'].FILES.get('image')
        file_bin = file.read()
        # 创建FastDFS客户端实例
        client = Fdfs_client(settings.FDFS_CONFIG_DIRS)
        # 调用FastDFS客户端上传文件方法
        ret = client.upload_by_buffer(file_bin)
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')
        instance.sku = validated_data['sku']
        instance.image =ret['Remote file_id']
        instance.save()
        # 异步生成静态文件
        get_static_sku_detail_html.delay(instance.sku.id)
        return instance



class SKUSerializer(ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id','name')

